import json

from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from Crypto.Util.Padding import pad
import base64
keys = "C0D2ACC1205B4028A4888CAC475FBE35"
class DECRYPT:
    @staticmethod
    def decrypt(encrypted_data):
        try:
            # # 将密钥转换为16/24/32字节长度
            key = keys.encode('utf-8')
            key = key.ljust(32, b'\0')[:32]  # 确保32字节
            # Base64解码
            encrypted_bytes = base64.b64decode(encrypted_data)
            # 创建解密器
            cipher = AES.new(key, AES.MODE_ECB)
            # 解密并去除填充
            decrypted = unpad(cipher.decrypt(encrypted_bytes), AES.block_size)
            return decrypted.decode('utf-8')
        except Exception as e:
            raise ValueError(f"AES解密失败: {str(e)}")
    @staticmethod
    def encrypt(data):
        try:
            # 1. 将字典转为 JSON 字符串
            json_data = json.dumps(data, ensure_ascii=False)
            # 2. 将字符串转为字节并填充
            padded_data = pad(json_data.encode('utf-8'), AES.block_size)
            key = keys.encode('utf-8')
            key = key.ljust(32, b'\0')[:32]  # 确保32字节
            cipher = AES.new(key, AES.MODE_ECB)
            ct_bytes = cipher.encrypt(padded_data)
            ct = base64.b64encode(ct_bytes).decode('utf-8')
            return ct
        except Exception as e:
            raise ValueError(f"AES加密失败: {str(e)}")